import request from '@/utils/request'

// 学生作业参数
export interface StudentAssignment {
  id?: number | string
  assignmentId: number | string // 作业模板ID
  assignmentTitle?: string
  studentId: number | string // 学生ID
  studentName?: string
  content?: string // 学生作业内容
  filePath?: string // 学生要上传的文件
  filePathForTeacher?: string // 学生要下载的文件（教师上传的文件）
  status:string // pending-批改中, completed-已完成, error-错误, wait-待提交
  gradingResultId?: number | string // 批改结果ID
  createTime?: string // 提交时间
  updateTime?: string // 更新时间
}

// 学生作业列表查询参数
export interface StudentAssignmentListParams {
  current: number
  pageSize: number
  assignmentId?: number | string
  studentId?: number | string
  status?: string
}

// 获取学生作业列表
export function getStudentAssignmentList(params: StudentAssignmentListParams) {
  return request.post<{
    code: number
    data: {
      total: number
      result: StudentAssignment[]
    }
    message: string
  }>('/studentAssignments/page', params)
}

// 获取学生作业详情
export function getStudentAssignment(id: number | string) {
  return request.get<{
    code: number
    data: StudentAssignment
    message: string
  }>(`/studentAssignments/get/${id}`)
}

// 创建学生作业
export function createStudentAssignment(data: StudentAssignment) {
  return request.post('/studentAssignments/create', data)
}

// 更新学生作业
export function updateStudentAssignment(data: StudentAssignment) {
  return request.post('/studentAssignments/update', data)
}

// 删除学生作业
export function deleteStudentAssignment(id: number | string) {
  return request.delete(`/studentAssignments/delete/${id}`)
}

// 批改作业 - 流式响应
export async function gradeStudentAssignment(
  assignmentId: number | string,
  onChunk?: (chunk: string) => void,
  onComplete?: () => void,
  onError?: (error: Error) => void
) {
  try {
    const response = await fetch(`http://8.134.190.228:8080/api-admin/studentAssignments/grade/${assignmentId}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': localStorage.getItem('AI_ASSISTANT_TOKEN') || '',
        'Accept': 'text/event-stream;charset=UTF-8'
      },
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const reader = response.body?.getReader()
    if (!reader) {
      throw new Error('无法获取响应流')
    }

    const decoder = new TextDecoder('utf-8')
    
    while (true) {
      const { done, value } = await reader.read()
      
      if (done) {
        onComplete?.()
        break
      }
      
      // 解码并处理响应内容
      const chunk = decoder.decode(value, { stream: true })
      onChunk?.(chunk)
    }
  } catch (error) {
    console.error('批改作业失败', error)
    onError?.(error as Error)
    throw error
  }
}